<template>
  <div class="login-setting">
    <el-form
      ref="userForm"
      :model="userInfo"
      :rules="rules"
      label-width="120px"
      style="margin-left: 120px; margin-top: 30px"
    >
      <el-form-item label="姓名:" prop="username">
        <el-input v-model="userInfo.username" style="width:300px" />
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="userInfo.password" type="password" style="width:300px" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="hSubmit">更新</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getUserDetail } from '@/api/user'
import { saveUserDetailById } from '@/api/employees'
export default {
  data() {
    return {
      // 表单数据项
      userInfo: {
        username: '',
        password: ''
      },
      // 表单校验规则
      rules: {
        username: [{ required: true, message: '用户名不能为空', triggler: 'blur' }],
        password: [{ required: true, message: '密码不能为空', triggler: 'blur' }]
      }
    }
  },
  created() {
    this.loadUserDetail()
  },
  methods: {
    // 请求用户数据 -> 表单回填
    async loadUserDetail() {
      try {
        const res = await getUserDetail(this.$route.query.id)
        console.log('loadUserDetail', res)
        this.userInfo = res.data
        // 保存数据
      } catch (err) {
        console.log('获取用户信息失败,原因是:', err)
      }
    },
    // 更新按钮 -> 兜底校验
    hSubmit() {
      this.$refs.userForm.validate(valid => {
        if (!valid) return
        // 校验成功 发送请求
        this.doUpdateUser()
      })
    },
    // 实现更新用户信息 -> 回退 保存数据
    async doUpdateUser() {
      try {
        const res = await saveUserDetailById(this.userInfo)
        console.log('更新用户信息', res)
        this.$message.success('修改成功')
        this.$router.back()
        // 保存数据
      } catch (err) {
        console.log('更新用户信息失败', err)
      }
    }
  }
}
</script>
